package com.pengtu.utils.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.pengtu.service.JbpmTemplateManager;

/**
 * Servlet implementation class TakeTaskeServlet
 */
public class PaintPngServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PaintPngServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String deploymentId = request.getParameter("deploymentId");
		String pngFileName = request.getParameter("pngFileName");
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		JbpmTemplateManager jbpmTemplateManager = (JbpmTemplateManager) ctx
				.getBean("jbpmTemplateManager");
		InputStream is = null;
		if (StringUtils.isNotEmpty(deploymentId)) {
			is = jbpmTemplateManager.getInputStream(deploymentId, pngFileName);
		}else{
			String id = request.getParameter("id");
			is = jbpmTemplateManager.getInputStreamById(id, pngFileName);
		}
		response.setContentType("image/png");
		byte[] bytes = new byte[1024];
		int size = 0;
		while ((size = is.read(bytes, 0, 1024)) != -1) {
			response.getOutputStream().write(bytes, 0, size);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
